<?php
//
namespace app\home\controller;

use app\common\model\ShopCartModel;
use app\common\model\ShopDeliveryModel;
use app\common\model\ShopGoodsSkuModel;
use app\common\model\ShopInvoiceModel;
use app\common\model\ShopOrderModel;
use app\common\model\ShopPaymentModel;
use app\common\model\ShopPromotionCardItemModel;
use app\common\model\UserAddressModel;
use think\Request;

class CartController extends BaseController
{

    private $cartModel;
    private $addressModel;
    private $deliveryModel;
    private $paymentModel;
    private $couponModel;
    private $goodSkuModel;
    private $orderModel;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        if ($this->getMemberUid() <= 0) {
            $url = url('home/Public/userLogin', ['url' => urlencode($_SERVER['HTTP_REFERER'])]);
            $this->error('请先登录！', $url, 'nologin');
        }
        $this->cartModel     = new ShopCartModel();
        $this->addressModel  = new UserAddressModel();
        $this->deliveryModel = new ShopDeliveryModel();
        $this->paymentModel  = new ShopPaymentModel();
        $this->invoiceModel  = new ShopInvoiceModel();
        $this->couponModel   = new ShopPromotionCardItemModel();
        $this->orderModel    = new ShopOrderModel();
        $this->goodSkuModel  = new ShopGoodsSkuModel();
    }

    /**
     * 购物车列表
     */
    public function index()
    {
        $cartStatus = $this->request->param('cart_status', 2);
        $cartList   = $this->cartModel->cartList($this->siteId, $this->getMemberUid(), $cartStatus);
        if ($this->request->isAjax()) {
            return json($cartList);
        }
        $this->assign('cartList', $cartList);
        return $this->fetch();
    }

    /**
     * 添加购物车
     */
    public function addCart()
    {
        $skuId  = $this->request->param('sku_id/d');
        $number = $this->request->param('number/d');
        $result = $this->cartModel->addCart($this->getMemberUid(), $skuId, $number);
        if ($result === false) {
            $this->error($this->cartModel->getError());
        }
        $this->success('添加成功！');
    }

    /**
     * 删除购物车
     */
    public function delCart()
    {
        $cartId = $this->request->param('cart_id/a');
        $this->cartModel->delCart($cartId);
        $this->success('删除成功！');
    }

    /**
     * 清空购物车
     */
    public function clearCart()
    {
        $cartStatus = $this->request->param('cart_status', 2);
        $this->cartModel->clearCart($this->siteId, $this->getMemberUid(), $cartStatus);
        $this->success('操作成功！');
    }

    /*
     * 订单确认
     */
    public function orderConfirm()
    {
        if ($this->request->has('sku_ids')) {
            $skuIds   = $this->request->param('sku_ids'); //商品sku_id,','隔开
            $cartList = $this->cartModel->cartList($this->siteId, $this->getMemberUid(), $skuIds);
            if (empty($cartList)) {
                $this->error('购买列表为空！');
            }
        } else {
            $cartList = $this->cartModel->cartList($this->siteId, $this->getMemberUid(), 1); //取有效列表
            if (empty($cartList)) {
                $this->error('购买列表为空！');
            }
            $skuIds = implode(',', array_column($cartList['item_list'], 'sku_id'));
        }
        if ($this->request->isAjax()) {
            return $cartList;
        }
        $skuIdsWeight = [];
        foreach ($cartList['item_list'] as $k => $v) {
            $skuIdsWeight[$v['sku_id']] = $v['num'];
        }
        //物流
        $delivery = $this->deliveryModel->where('site_id', $this->siteId)->where('status', 1)->order('is_default desc')->select();
        //获取优惠券
        $couponList = $this->couponModel->getMyCardList('unused', $this->getMemberUid(), $this->siteId, $cartList['total_price'], '100');
        //dump($couponList);
        $this->assign('couponList', $couponList);
        $this->assign('skuIds', $skuIds);
        $this->assign('skuIdsWeight', $skuIdsWeight);
        $this->assign('delivery', $delivery);
        $this->assign('cartList', $cartList);
        return $this->fetch();
    }

    /*获取发票信息*/
    function getInvlist()
    {
        $invState          = $this->request->param('inv_state');
        $map               = [];
        $map['member_uid'] = $this->getMemberUid();
        $map['inv_state']  = $invState;
        $list              = $this->invoiceModel->where($map)->select();
        return $list;
    }

    /*获取配送费
    */
    function getDeliveryprice()
    {
        $skuIdsWeight = $this->request->param('skuids_weight/a');
        $deliveryId   = $this->request->param('delivery_id');
        $goodsAmount  = $this->request->param('goods_amount');
        $shippingFee  = $this->deliveryModel->calculateFreight($skuIdsWeight, $deliveryId, $goodsAmount);
        return $shippingFee;
    }

    /*提交订单
    */
    function submitOrder()
    {
        if ($this->request->isPost()) {
            $data               = $this->request->param();
            $data['member_uid'] = $this->getMemberUid();
            $result             = $this->orderModel->subOrder(
                $data['order_type'],
                $data['sku_ids'],
                $data['member_uid'],
                $data['site_id'],
                $data['address_id'],
                $data['card_key'],
                1,
                $data['order_message'],
                $data['delivery_id'],
                $data['inv_id'],
                $data['pay_code']);
            if ($result === false) {
                $this->error($this->orderModel->getError());
            }
            $this->success('订单提交成功', url('payOrder', ['order_sn' => $result]));
        }
    }

    /**
     * 订单支付
     * @return mixed
     */
    function payOrder()
    {
        $orderSn                   = $this->request->param('order_sn');
        $moudle=$this->request->param('moudle',0);
        $tpl=$this->request->param('tpl',0);
        if ($moudle){
            $model=model($moudle);
            $orderInfo                 = $model->where('order_sn', $orderSn)->find();
        }else{
            $orderInfo                 = $this->orderModel->where('order_sn', $orderSn)->find();
        }
        $device                    = is_mobile();
        if ($device == 3) { //微信端需先获取用户openid
            if (!$this->request->has('openid')) {
                $this->redirect('plus/Wxpay/getOpenid', ['site_id' => $orderInfo['site_id'], 'url' => urlencode(get_current_url())]);
            } else {
                $param['openid']     = $this->request->param('openid');
                $param['site_id']    = $orderInfo['site_id'];
                $param['order_type'] = 'order';
                $param['order_sn']   = $orderInfo['order_sn'];
                $param['device']     = $device;
                $url = url('plus/Wxpay/pay',['_ajax'=>1],true,true);
                $result = send_http($url,$param,'POST');
                $result = json_decode($result,true);
                $this->assign('jsApiParameters',$result['data']);
            }
        }
        //支付方式
        $payment = $this->paymentModel->getList($this->siteId);
        $this->assign('payment', $payment);
        $this->assign('orderInfo', $orderInfo);
        $this->assign('device', $device); //1、手机端 2电脑端 3微信端
        return $this->fetch($tpl?:'');
    }

}
